/**
 * 页面导航工具
 * @module Nav
 */
import * as base from '@/common/sju.base.js'
import * as login from '@/common/sju.login.js'
// 默认配置
import { t } from '@/common/sju.i18n.js'

// 路径类型常量
const PATH_TYPES = {
  ROOT: '/pages/',
  TAB: '/pages/tab/',
  SUBPACKAGE: '/sub_'
}

/**
 * URL路径转换
 * @param {string} url 原始路径
 * @returns {string} 转换后的路径
 */
function transferUrl(url) {
  const [path, query] = url.split('?')
  const segments = path.split('/').filter(Boolean)
  let result = ''

  switch(segments.length) {
    case 1: // /page
      result = PATH_TYPES.ROOT
      break
    case 2: // /type/page
      result = segments[0] === 'tab' 
        ? PATH_TYPES.TAB 
        : `${PATH_TYPES.SUBPACKAGE}${segments[0]}/pages/`
      break
    default:
      throw new Error(proxy.$t('common.nav.invalid_path_format', { url }))
  }

  const pageName = segments[segments.length - 1]
  result += `${pageName}/${pageName}`
  if (query) result += `?${query}`

  base.logInfo(t('common.nav.url_transfer_log', { url, result }))
  return result
}

/**
 * 统一导航处理
 * @private
 * @param {function} navMethod 导航方法
 * @param {string} url 目标URL
 */
function _navigate(navMethod, url) {
  if (!login.checkLogin(url)) return

  try {
    const formattedUrl = transferUrl(url)
    navMethod({ url: formattedUrl })
  } catch (error) {
    base.logInfo(t('common.nav.navigate_fail_log', { method: navMethod.name, message: error.message }))
    throw error
  }
}

/**
 * 保留当前页面跳转
 * @param {string} url 目标URL
 */
function navigateTo(url) {
  _navigate(uni.navigateTo, url)
}

/**
 * 关闭当前页面跳转
 * @param {string} url 目标URL
 */
function redirectTo(url) {
  _navigate(uni.redirectTo, url)
}

/**
 * 关闭所有页面跳转
 * @param {string} url 目标URL
 */
function reLaunch(url) {
  _navigate(uni.reLaunch, url)
}

/**
 * 跳转至Tab页
 * @param {string} url 目标URL
 */
function switchTab(url) {
  _navigate(uni.switchTab, url)
}

/**
 * 返回上一页
 * @param {number} [delta=1] 返回层数
 */
function navigateBack(delta = 1) {
  uni.navigateBack({ delta })
}

export {
  navigateTo,
  redirectTo,
  reLaunch,
  switchTab,
  navigateBack
}
